package com.bgrc.hubu12305.config;

import com.bgrc.hubu12305.filter.MyFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 包名:com.bgrc.hubu12305.config
 * 用户:86182
 * 时间:20211222:142021/12/10
 */
@Slf4j
@Configuration
public class ShiroConfig {
    //3.创建ShiroFilterFactoryBean绑定securityManager
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getSecurityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        factoryBean.setSecurityManager(securityManager);
        //添加shiro内置过滤器
        /*
            anon:无需认证就可以访问
            authc:必须认证了才能访问
            user:必须拥有 记住我 这个功能才能访问
            role:拥有某个角色权限才能访问
        * */
        //拦截

        Map<String, Filter> filters = factoryBean.getFilters();
        filters.put("authc", new MyFilter());
        factoryBean.setFilters(filters);
        Map<String,String> filterMap = new LinkedHashMap<>();
        //设置权限
        //System.out.println("授权前");

        //filterMap.put("/user/test","perms[user:test]");

        //System.out.println("授权后");
        filterMap.put("/user/login","anon");
        filterMap.put("/user/logout","anon");
        filterMap.put("/user/register","anon");

        filterMap.put("/user/*","authc");
        filterMap.put("/user/test","authc");
        filterMap.put("/order","authc");
        filterMap.put("/train/*","authc");
        filterMap.put("/admin/*","authc");

        factoryBean.setFilterChainDefinitionMap(filterMap);
        //factoryBean.setLoginUrl("/user/login");

        return factoryBean;
    }

    //2.创建Manage绑定Realm对象
    @Bean
    public DefaultWebSecurityManager getSecurityManager(ShiroRealm shiroRealm,
                                                        UserSessionManage userSessionManage){

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(userSessionManage);
        securityManager.setRealm(shiroRealm);
        return securityManager;
    }
    //1.创建Realm对象，需要自定义类继承AuthorizingRealm
    @Bean
    public ShiroRealm userRealm(){
        return new ShiroRealm();
    }
}
